package com.atguigu.tingshu.user.strategy.impl;
import java.util.Date;
import com.google.common.collect.Maps;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.service.UserPaidTrackService;
import com.atguigu.tingshu.user.strategy.UpdateUserPaidRecordStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
// 声音购买保存交易信息的策略
public class UserPaidTrackStrategy implements UpdateUserPaidRecordStrategy {
    @Autowired
    private UserPaidTrackService userPaidTrackService;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;
    @Override
    public void updateUserPaid(UserPaidRecordVo userPaidRecordVo) {
        //防止重复消费
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getOrderNo,userPaidRecordVo.getOrderNo());
        long count = userPaidTrackService.count(queryWrapper);

        if(count>0) return;
        //根据声音id查询声音信息
        TrackInfo trackInfo = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0)).getData();
        //声音购买信息
        List<Long> itemIdList = userPaidRecordVo.getItemIdList();
        List<UserPaidTrack> collect = itemIdList.stream().map(itemId -> {
            //封装声音信息
            UserPaidTrack userPaidTrack = new UserPaidTrack(); //通过该对象封装对应的信息
            userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
            userPaidTrack.setUserId(userPaidRecordVo.getUserId());
            userPaidTrack.setAlbumId(trackInfo.getAlbumId());
            userPaidTrack.setTrackId(itemId);
            return userPaidTrack;
        }).collect(Collectors.toList());
        //保存声音购买信息存储到数据库
        userPaidTrackService.saveBatch(collect);
    }

    @Override
    public String getItemType() {
        return SystemConstant.ORDER_ITEM_TYPE_TRACK;
    }
}
